package com.hongxun.design.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.zxing.WriterException;
import com.hongxun.design.BroadCastReceivers.WifiStateBroadCast;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.adapters.ClientInfoGridAdapter;
import com.hongxun.design.bean.ScanHotBean;
import com.hongxun.design.bean.service.ClientInfo;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.Global;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.FileSizeUtil;
import com.hongxun.design.utils.fileutil.ZipUtil;
import com.hongxun.design.utils.imageutil.UriUtil;
import com.hongxun.design.utils.serviceandclient.ClientUtil;
import com.hongxun.design.utils.serviceandclient.ServiceUtil;
import com.hongxun.design.utils.wifiutil.OpretionsType;
import com.hongxun.design.utils.wifiutil.WiFiUtil;
import com.hongxun.design.utils.wifiutil.WifiHostConnect;
import com.hongxun.design.utils.wifiutil.WifiHostSearch;
import com.hongxun.design.utils.wifiutil.WifiHostUtil;
import com.zbar.lib.CaptureActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import zxing.encode.CodeCreator;

/**
 * Created by zerdoor_pc on 2016/7/21.
 * 面对面发送与接收界面
 */
public class FaceSendAndReceiveActivity extends BaseActivity implements HeadSecond, WifiStateBroadCast.WifiBroadCastOperations {
    int type = 0;
    int view = View.VISIBLE;
    String title = "";
    HeadSecondControlPanel headsecond_layout;
    SimpleDraweeView code_image;
    /**
     * 面对面快传*
     */
    String stage_id;
    public String projectcode = "";
    private static final int REQUEST_CODE_SCAN = 0x0000;
    String SSID = "";

    TextView search_left, code_right, clientinfo_name, send_words, recive_code, recive_project;
    RelativeLayout code_item, search_other, receive_other, service_info;
    GridView service_grid;
    LinearLayout loading, loading_grid;
    SimpleDraweeView clientinfo_icon;//接收端头像
    LinearLayout face_bottom_send_receive, face_bottom_choice;//底部切换按钮
    ProgressBar send_progress;
    /**
     * 接收信息*
     */
    ScanHotBean bean;
    Handler serviceUtilHandler;
    Handler clientUtilHandler;

    List<ClientInfo> clientInfoList;
    ClientInfoGridAdapter infoListadapter;
    ClientInfo serviceInfo;
    ServiceUtil service;
    ClientUtil client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_facesendandreceive);
        MyLog.L(MString.service + " setUpdate_onCreate");
        findBar();
        findView();
    }

    @Override
    public void findBar() {
        MyLog.L(MString.service + " setUpdate_findBar");
        headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.facesendandreceive_layout);
        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt(MString.TYPE);
        switch (type) {
            case Constant.send:
                title = "发送";
                view = View.VISIBLE;
                stage_id = bundle.getString(MString.stage_id);
                projectcode = bundle.getString(MString.CODE);
                break;
            case Constant.receive:
                title = "接收";
                view = View.GONE;
                break;
        }

        headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", view, R.color.bar_right, ListenerSet.back, title, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        if (type == Constant.send) {
            headsecond_layout.setClickListener(listener);
        }

    }

    View.OnClickListener listener=new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (service == null) service = new ServiceUtil(serviceUtilHandler);
            int i = service.setInfoList(clientInfoList);//遍历设置选定发送的线程
            if (i == 0) {
                ToastShow.showShort(mActivity, "请至少选择一个用户！");
                return;
            }

//          ProjectToIOSBean bean=new ProjectToIOSBean();
//          bean.setBean(FastJsonUtil.JsonToGetProject(projectcode));
            ScanHotBean scanHotBean=new ScanHotBean(MString.projectInfo, JSON.toJSONString(FastJsonUtil.JsonToGetProject(projectcode)));
            MyLog.L(MString.service + " s=" + JSON.toJSONString(scanHotBean));
            try {
                String PATH = mActivity.getFilesDir().getPath() + File.separator;
                final String name = "ProjectStage_" + stage_id;
                String path=  PATH + MyApp.openIdent + "/FaceFile/"+name;
                String pathload=  path+File.separator+MString.Request;//上传
                String pathcache= path+File.separator+MString.Response;//本地
                File file=new File(path);
                File fileload=new File(pathload);
                File filecache=new File(pathcache);
                if (file.exists()){
                    file.delete();
                }
                fileload.mkdirs();
                filecache.mkdirs();
                MyApp.File.copyFolder(PATH + MyApp.openIdent + File.separator + name, pathcache);//复制本地缓存文件夹
                MyApp.File.copyFolder(PATH + MyApp.openIdent + File.separator + MString.Request + File.separator+ name,pathload);//复制同步文件夹
                final String zipFilePath = ZipUtil.zipFolder(path);


//                String zipFilePath = ZipUtil.zipFolder(PATH + MyApp.openIdent + File.separator + name);
                service.sendMessage(JSON.toJSONString(scanHotBean));
                ServiceUtil.isSend=false;
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        service.sendMessage(zipFilePath, name + ".zip");//发送文件返回大小
                    }
                },1000);

            } catch (Exception e) {
                e.printStackTrace();
            }
            changeTo(1);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        MyLog.L(MString.service + " setUpdate_onDestroy");
        clientUtilHandler = null;
        serviceUtilHandler = null;
        if (client != null) client.close();
        if (service != null) service.close();
        if (WifiHostUtil.getInstance(this).wifiIsOpen()) {
            WifiHostUtil.getInstance(this).closeWifi();
        } else {
            WifiHostUtil.getInstance(this).openWifi();
        }
        service = null;
        client = null;
        WifiHostConnect.getInstance(this).clear();
        WifiHostSearch.getInstance(this).clear();
        super.onDestroy();
    }

    @Override
    protected void findView() {
        super.findView();
        MyLog.L(MString.service + " setUpdate_findView");
        search_left = (TextView) findViewById(R.id.search_left);
        code_right = (TextView) findViewById(R.id.code_right);
        send_words = (TextView) findViewById(R.id.send_words);
        face_bottom_choice = (LinearLayout) findViewById(R.id.face_bottom_choice);
        face_bottom_send_receive = (LinearLayout) findViewById(R.id.face_bottom_send_receive);
        send_progress = (ProgressBar) findViewById(R.id.send_progress);
        changeTo(0);
        SetTypeface.set(search_left, IconSourse.faceSearch);
        SetTypeface.set(code_right, IconSourse.ERWEIMA);
        if (type == Constant.send) {
            MyLog.L(MString.service + " setUpdate_findView_send");
            findView_send();
        } else {
            MyLog.L(MString.service + " setUpdate_findView_Receive");
            findView_Receive();
        }
        LeftButton(search_left);
        initialization();
    }

    /**
     * 打开service*
     */
    private void openService() {
        addServiceUtilHandler();
        if (service == null) service = new ServiceUtil(serviceUtilHandler);

    }

    /**
     * 打开socket*
     */
    private void openClient() {
        // addClientUtilHandler();
        client = new ClientUtil();
    }

    /**
     * 切换接收与连接页面*
     */
    private void changeTo(int type) {
        if (type == 0) {//初始进入状态
            face_bottom_choice.setVisibility(View.VISIBLE);
            face_bottom_send_receive.setVisibility(View.GONE);

        } else {
            //传输与接收状态
            face_bottom_choice.setVisibility(View.GONE);
            face_bottom_send_receive.setVisibility(View.VISIBLE);
            headsecond_layout.mleftTitle.setVisibility(View.GONE);
            headsecond_layout.mRightTitle.setVisibility(View.VISIBLE);
            headsecond_layout.mRightTitle.setText("取消");
            headsecond_layout.mRightTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    changeTo(0);
                }
            });
        }
    }

    @SuppressLint("NewApi")
    private void changeBack(){
        headsecond_layout.mleftTitle.setVisibility(View.VISIBLE);
        headsecond_layout.mRightTitle.setVisibility(View.VISIBLE);
        search_left.setTextColor(getResources().getColor(R.color.white));
        code_right.setTextColor(getResources().getColor(R.color.yellow_l));
        search_left.setBackgroundResource(R.drawable.yellow_c8_item);
        code_right.setBackground(null);
        headsecond_layout.mRightTitle.setText("确认发送");
        headsecond_layout.mRightTitle.setOnClickListener(listener);
    }

    @Override
    protected void initialization() {
        super.initialization();
        switch (type) {
            case Constant.send:
                initialization_send();
                break;
            case Constant.receive:
                initialization_Receive();
                break;
        }
    }

    /**
     * 发送*
     */
    void findView_send() {
        search_left.append(" 搜索附近");
        code_right.append(" 二维码发送");
        //打开热点

        search_other = (RelativeLayout) findViewById(R.id.search_other);
        loading_grid = (LinearLayout) findViewById(R.id.loading_grid);
        service_grid = (GridView) findViewById(R.id.service_grid);
        loading_grid.setVisibility(View.VISIBLE);
        service_grid.setVisibility(View.GONE);
        code_item = (RelativeLayout) findViewById(R.id.code_item);
        TextView code_hot = (TextView) findViewById(R.id.code_hot);
        code_image = (SimpleDraweeView) findViewById(R.id.code_image);
//        code_hot.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                ScanHotBean scanHotBean = new ScanHotBean(MString.android, SSID, MyApp.userInfo.getUsername(), MyApp.userInfo.getAvatar());
//                MyDialog.openCodeImage(mActivity, JSON.toJSONString(scanHotBean));
//            }
//        });

        clientInfoList = new ArrayList<>();
        //  if (clientInfoList.size() == 0) clientInfoList.add(new ClientInfo());
        infoListadapter = new ClientInfoGridAdapter(clientInfoList, this);
        service_grid.setAdapter(infoListadapter);
        creatWifiHost();

    }

    /**
     * 接收*
     */
    void findView_Receive() {
        addClientUtilHandler();
        search_left.append(" 搜索附近");
        code_right.append(" 二维码扫描");
        receive_other = (RelativeLayout) findViewById(R.id.receive_other);
        loading = (LinearLayout) findViewById(R.id.loading);
        service_info = (RelativeLayout) findViewById(R.id.service_info);
        clientinfo_icon = (SimpleDraweeView) findViewById(R.id.clientinfo_icon);
        clientinfo_name = (TextView) findViewById(R.id.clientinfo_name);
        recive_code = (TextView) findViewById(R.id.recive_code);
        recive_project = (TextView) findViewById(R.id.recive_project);
        service_info.setVisibility(View.GONE);
        receive_other.setVisibility(View.VISIBLE);
        connect();
    }

    private void 扫一扫() {
        TextView receive_code = (TextView) findViewById(R.id.receive_code);
        receive_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bun = new Bundle();
                bun.putString(MString.TITLE, MString.ScanAndScan);
                bun.putString(MString.TYPE, MString.ScanToFind);
                IntentToActivity.intentActivityForResult(mActivity, CaptureActivity.class, bun, REQUEST_CODE_SCAN);
            }
        });
    }

    void initialization_send() {

    }

    void initialization_Receive() {


    }

    /**
     * 搜索点击*
     */
    public void LeftButton(View v) {
        changeStyle(0);
        if (type == Constant.send) {
            code_item.setVisibility(View.GONE);
            search_other.setVisibility(View.VISIBLE);
        } else {

        }
    }

    /**
     * 二维码点击*
     */
    public void RightButton(View v) {
        changeStyle(1);
        if (type == Constant.send) {
            try {
                ScanHotBean scanHotBean = new ScanHotBean(MString.android, SSID, MyApp.userInfo.getUsername(), MyApp.userInfo.getAvatar());
                Bitmap bitmap = CodeCreator.createQRCode(JSON.toJSONString(scanHotBean));
                code_image.setImageBitmap(bitmap);
            } catch (WriterException e) {
                e.printStackTrace();
            }
            search_other.setVisibility(View.GONE);
            code_item.setVisibility(View.VISIBLE);

        } else {
            Bundle bun = new Bundle();
            bun.putString(MString.TITLE, MString.ScanAndScan);
            bun.putString(MString.TYPE, MString.ScanToFind);
            IntentToActivity.intentActivityForResult(mActivity, CaptureActivity.class, bun, REQUEST_CODE_SCAN);
            changeStyle(0);

//            loading.setVisibility(View.GONE);
//            service_info.setVisibility(View.VISIBLE);
            // serviceInfo = client.getServiceInfo();
            // clientUtilHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 按钮状态切换*
     */
    @SuppressLint("NewApi")
    void changeStyle(int index) {
        if (index == 0) {
            search_left.setTextColor(getResources().getColor(R.color.white));
            code_right.setTextColor(getResources().getColor(R.color.yellow_l));
            search_left.setBackgroundResource(R.drawable.yellow_c8_item);
            code_right.setBackground(null);
            headsecond_layout.mRightTitle.setText("确认发送");
            headsecond_layout.mRightTitle.setOnClickListener(listener);
        } else {
            code_right.setTextColor(getResources().getColor(R.color.white));
            search_left.setTextColor(getResources().getColor(R.color.yellow_l));
            code_right.setBackgroundResource(R.drawable.yellow_c8_item);
            search_left.setBackground(null);
            headsecond_layout.mRightTitle.setText("");
        }

    }

    /**
     * *******************************二维码回调******************************************************
     */


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(MString.codedContent);
                bean = FastJsonUtil.getScanHotBean(content);
                if (!bean.getDeviceType().equals(MString.android)) {
                    creatWifiHost();
                    bean.setHotName(SSID);
                    //openService();
                }

                MyDialog.openCodeResult(this, bean);
            }
        }
    }

    /************************************服务器与客户端*****************************************************/
    /**
     * 打开服务器*
     */
    public void startService() {
        //service.close();
        MyLog.L(MString.service + " setUpdate_startService" + service);
        openService();
        service.start();
    }

    /**
     * 加载服务器handler*
     */

    void addServiceUtilHandler() {
        if (serviceUtilHandler == null) serviceUtilHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        if (clientInfoList == null) {
                            if (clientUtilHandler!=null)clientUtilHandler.sendEmptyMessage(4);
                            return;
                        }
                        try {

                        clientInfoList.clear();
                        clientInfoList.addAll(service.getInfoList());
                        MyLog.L(MString.service + " setUpdate_clientInfoList" + clientInfoList);
                        MyLog.L(MString.service + " setUpdate_clientInfoList.size" + clientInfoList.size());
                        if (clientInfoList.size() > 0) {
                            loading_grid.setVisibility(View.GONE);
                            service_grid.setVisibility(View.VISIBLE);
                        } else {
                            loading_grid.setVisibility(View.VISIBLE);
                            service_grid.setVisibility(View.GONE);
                        }
                        infoListadapter.notifyDataSetChanged();
                        changeTo(0);
                        changeBack();

                        }catch (Exception e){}
                        break;
                    case 1:
                        if (msg.arg1 != -1) {
                            int proess = msg.arg1 * msg.arg2;
                            send_words.setText("共" + FileSizeUtil.FormetFileSize(Long.parseLong("" + msg.obj)) + ",已传输" + proess + "%");
                            send_progress.setProgress(proess);
                        } else {
                            SetTypeface.set(send_words, IconSourse.checked);
                            send_words.append("发送完成");
                            send_progress.setVisibility(View.GONE);
                            headsecond_layout.mRightTitle.setText("完成");
                            headsecond_layout.mRightTitle.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    WifiHostUtil.getInstance(mActivity).closeWifi();
                                    finish();
                                }
                            });
                        }
                        break;
                    case 2:
                        creatWifiHost();
                        break;
                    case 3:
//                        send_words.setText("正在接收项目");
                        recive_project.setText((CharSequence) msg.obj);
                        recive_code.setText("正在向你发送项目");
                        recive_code.setVisibility(View.VISIBLE);
//                        changeTo(1);
                        break;
                    case 200:
                        int proess = msg.arg2;
                        if (msg.arg1 != -1&&msg.arg1 != -2&&proess!=100) {
                            if (msg.obj != null) {
                                send_words.setText("共" + FileSizeUtil.FormetFileSize(Long.parseLong("" + msg.obj)) + ",已接收" + proess + "%");
                                send_progress.setProgress(proess);
                            }
                        } else if (msg.arg1 == -1|| proess==100){
                            SetTypeface.set(send_words, IconSourse.checked);
                            send_words.append("接收完成");
                            send_progress.setProgress(100);
                            send_progress.setVisibility(View.GONE);
                            headsecond_layout.mRightTitle.setText("完成");
                            headsecond_layout.mRightTitle.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    WifiHostUtil.getInstance(mActivity).closeWifi();
                                    finish();
                                }
                            });

                            recive_code.setText("已向你发送项目:");
                            recive_project.setVisibility(View.VISIBLE);

                            face_bottom_choice.setVisibility(View.GONE);
                            face_bottom_send_receive.setVisibility(View.VISIBLE);
                            headsecond_layout.mleftTitle.setVisibility(View.GONE);
                            headsecond_layout.mRightTitle.setVisibility(View.VISIBLE);

                        }else if (msg.arg1 == -2){
                            SetTypeface.set(send_words, IconSourse.checked);
                            send_words.append("权限不足,接收失败！");
                            send_progress.setProgress(0);
                            send_progress.setVisibility(View.GONE);
                            headsecond_layout.mRightTitle.setText("完成");
                            headsecond_layout.mRightTitle.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    WifiHostUtil.getInstance(mActivity).closeWifi();
                                    finish();
                                }
                            });
                            recive_code.setText("已向你发送项目:");
                            recive_project.setVisibility(View.VISIBLE);
                        }
                        break;
                }
            }
        };

    }

    /**
     * 打开客服端*
     */
    public synchronized void startClient() {
        MyLog.L(MString.service + " setUpdate_startClient");
        // client.close();
        // MyLog.L(MString.service + " setUpdate_startClient"+client);
        if (client == null) openClient();
        // MyLog.L(MString.service + " setUpdate_startClient" + client);
        client.start(this, clientUtilHandler);
    }

    /**
     * 加载客服端handler*
     */

    void addClientUtilHandler() {
        MyLog.L(MString.service + " setUpdate_addClientUtilHandler");
        clientUtilHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0://更新
                        if (client!=null)serviceInfo = client.getServiceInfo();
                        if (serviceInfo == null) return;
                        MyLog.L(MString.service + " 更新 serviceInfo=" + serviceInfo.getUserName());
                        MyLog.L(MString.service + " 更新 serviceInfo=" + serviceInfo.getUserAvatar());
                        if (serviceInfo.getUserAvatar().length() == 0 && serviceInfo.getUserName().length() == 0) {
                            loading.setVisibility(View.VISIBLE);
                            service_info.setVisibility(View.GONE);
                        } else {
                            clientinfo_icon.setImageURI(UriUtil.getUri(serviceInfo.getUserAvatar()));
                            clientinfo_name.setText(serviceInfo.getUserName());
                            loading.setVisibility(View.GONE);
                            service_info.setVisibility(View.VISIBLE);
                        }
                        break;
                    case 1://重连接
                        startClient();
                        break;
                    case 3:
                        changeTo(0);
                        connect();
                        break;
                    case 2:
                        recive_project.setText((CharSequence) msg.obj);
                        recive_code.setText("正在向你发送项目");
                        recive_code.setVisibility(View.VISIBLE);
                        changeTo(1);
                        break;
                    case 4:
                        List<ClientInfo> servicelist = service.getInfoList();
                        if (servicelist.size() == 1) {
                            serviceInfo = servicelist.get(0);
                            MyLog.L(MString.service + " 更新 serviceInfo=" + serviceInfo.getUserName());
                            MyLog.L(MString.service + " 更新 serviceInfo=" + serviceInfo.getUserAvatar());
                            clientinfo_icon.setImageURI(UriUtil.getUri(serviceInfo.getUserAvatar()));
                            clientinfo_name.setText(serviceInfo.getUserName());
                            loading.setVisibility(View.GONE);
                            service_info.setVisibility(View.VISIBLE);
                        }
                        break;
                    case 200:

                        MyLog.L(MString.service2 + " 接收到：== msg.arg1=" + msg.arg1+" msg.arg2="+msg.arg2+"  msg.obj"+msg.obj);
                        int proess = msg.arg2;
                        if (msg.arg1 != -1&&msg.arg1 != -2&&proess!=100) {
                            if (msg.obj != null) {
                                send_words.setText("共" + FileSizeUtil.FormetFileSize(Long.parseLong("" + msg.obj)) + ",已接收" + proess + "%");
                                send_progress.setProgress(proess);
                            }
                        } else if (msg.arg1 == -1|| proess==100){
                            SetTypeface.set(send_words, IconSourse.checked);
                            send_words.append("接收完成");
                            send_progress.setProgress(100);
                            send_progress.setVisibility(View.GONE);
                            recive_code.setText("已向你发送项目:");
                            recive_project.setVisibility(View.VISIBLE);
                            headsecond_layout.mRightTitle.setText("完成");
                            headsecond_layout.mRightTitle.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    finish();
                                }
                            });
                        }else if (msg.arg1 == -2){
                            SetTypeface.set(send_words, IconSourse.checked);
                            send_words.append("权限不足,接收失败！");
                            send_progress.setProgress(0);
                            send_progress.setVisibility(View.GONE);
                            recive_code.setText("已向你发送项目:");
                            recive_project.setVisibility(View.VISIBLE);
                            headsecond_layout.mRightTitle.setText("完成");
                            headsecond_layout.mRightTitle.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                    finish();
                                }
                            });
                        }

                        break;
                }
            }
        };

    }
    /************************************wifi热点连接*****************************************************/
    /**
     * 热点搜索
     */
    private List<ScanResult> wifiList;
    public boolean connected = false;
    private String mSSID;

    /**
     * 创建热点*
     */

    private void creatWifiHost() {
        MyLog.L(MString.service + " setUpdate_creatWifiHost");
        SSID = WiFiUtil.creatWifiHost(this);
    }

    /**
     * 连接热点*
     */
    private void connect() {
        //连接热点
        MyLog.L(MString.service + " setUpdate_connect");
        WiFiUtil.searchHost(this);
    }

    /**
     * 搜索热点*
     */
    private void searchHost() {
        WifiHostSearch.getInstance(this).scanWifiHot();
    }

    //wifi搜索返回结果
    @Override
    public void disPlayWifiScanResult(List<ScanResult> wifiList) {
        MyLog.L(MString.service + " setUpdate_disPlayWifiScanResult");
        findViewAndAddData(wifiList);
    }

    @Override
    public boolean disPlayWifiConResult(boolean result, WifiInfo wifiInfo) {
        MyLog.L(MString.service + " setUpdate_disPlayWifiConResult");
        MyLog.L(MyApp.AppName + "into 热点连接回调函数");
        String ip = "";
        WifiHostConnect wifiHostConnect = WifiHostConnect.getInstance(this);
        wifiHostConnect.setConnectStatu(false);
        WifiHostSearch.getInstance(this).unRegisterWifiStateBroadCast();
        wifiHostConnect.unRegisterWifiConnectBroadCast();
        MyLog.L(MyApp.AppName + "out 热点链接回调函数");
        // addClientUtilHandler();
        clientUtilHandler.sendEmptyMessage(1);

        return false;

    }

    @Override
    public void operationByType(OpretionsType type, String SSID) {
        MyLog.L(MString.service + " setUpdate_operationByType");
        MyLog.L(MyApp.AppName + "into operationByType！type = " + type);
        if (type == OpretionsType.CONNECT) {
            WifiHostConnect.getInstance(this).connectToHotpot(SSID, wifiList, Global.PASSWORD);
        } else if (type == OpretionsType.SCAN) {
            WifiHostSearch.getInstance(this).scanWifiHot();
        }
        MyLog.L(MyApp.AppName + "out operationByType！");
    }

    /**
     * 热点搜索数据适配处理
     */
    private void findViewAndAddData(List<ScanResult> wifiList) {

        WifiHostSearch.getInstance(this).unRegisterWifiScanBroadCast();
        this.wifiList = wifiList;
        MyLog.L(MyApp.AppName + "out 热点扫描结果 ： = " + wifiList);
        if (wifiList.size() == 1 && !connected) {
            connected = true;
            ScanResult result = wifiList.get(0);
            mSSID = result.SSID;
            MyLog.L(MyApp.AppName + "into  onItemClick() SSID= " + result.SSID);
            WifiHostConnect.getInstance(this).connectToHotpot(result.SSID, wifiList, Global.PASSWORD);
            MyLog.L(MyApp.AppName + "out  onItemClick() SSID= " + result.SSID);
        }

    }


}
